from django.contrib import admin, messages

from django.shortcuts import redirect

from core.models import Commune, Country, Post, Program, ProgramModule, CourseGroup

admin.site.disable_action('delete_selected')

class ProtectedModelAdmin(admin.ModelAdmin):
  def delete_view(self, *args, **kwargs):
    try:
      return super(ProtectedModelAdmin, self).delete_view(*args, **kwargs)
    except Exception, e:
      request = args[0]
      messages.error(request, e.args[0])
      
      new_path = request.path.split('/')
      if new_path[-1] == '':
        new_path = new_path[:-2]
      else:
        new_path = new_path[:-1]
      return redirect('/'.join(new_path))

class CommuneAdmin(ProtectedModelAdmin):
  list_display = ('code', 'name', 'inactive',)
  list_editable = ['name', 'inactive']
  search_fields = ['code', 'name']
  
class CountryAdmin(ProtectedModelAdmin):
  list_display = ('code', 'name', 'international_name', 'inactive',)
  list_editable = ['name', 'international_name', 'inactive']
  search_fields = ['code', 'name', 'international_name']

class PostAdmin(ProtectedModelAdmin):
  list_display = ('code', 'name', 'inactive',)
  list_editable = ['name', 'inactive']
  search_fields = ['code', 'name']

class SubjectProgramInline(admin.TabularInline):
  model = Program.subjects.through
  extra = 0

class ProgramAdmin(ProtectedModelAdmin):
  list_display = ('code', 'name', 'inactive',)
  list_editable = ['name', 'inactive']
  search_fields = ['code', 'name']
  inlines = [SubjectProgramInline]
  
class ProgramModuleAdmin(ProtectedModelAdmin):
  list_display = ('name', 'year', 'inactive',)
  list_editable = ['year', 'inactive']
  search_fields = ['name']
  
class CourseGroupAdmin(ProtectedModelAdmin):
  list_display = ('code', 'name', 'inactive',)
  list_editable = ['name', 'inactive']
  search_fields = ['code', 'name']

admin.site.register(Commune, CommuneAdmin)
admin.site.register(Country, CountryAdmin)
admin.site.register(Post, PostAdmin)
admin.site.register(Program, ProgramAdmin)
admin.site.register(ProgramModule, ProgramModuleAdmin)
admin.site.register(CourseGroup, CourseGroupAdmin)
